package org.automated.realestatemanager.parserutils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.log4j.Logger;

public class HTTPClient {
	private static final Logger log = Logger.getLogger(HTTPClient.class);

	public static String getWebPage(final String urlString) {
		final StringBuilder result = new StringBuilder();
		URL url = null;
		try {
			url = new URL(urlString);
		} catch (final MalformedURLException e) {
			log.error("Wrong URL" + urlString);
			e.printStackTrace();
		}
		HttpURLConnection connection = null;
		try {
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("GET");
			final BufferedReader rd = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			System.out.println("Encording " + connection.getContentEncoding());
			while (rd.readLine() != null) {
				// System.out.println(rd.readLine());
				result.append(rd.readLine());
			}
		} catch (final IOException e) {
			log.error("IO exception occured");
			e.printStackTrace();
		} finally {
			connection.disconnect();
		}

		return result.toString();
	}

	public static InputStream getStream(final String urlString) {
		InputStream result = null;
		URL url = null;
		try {
			url = new URL(urlString);
		} catch (final MalformedURLException e) {
			log.error("Wrong URL" + urlString);
			e.printStackTrace();
		}
		HttpURLConnection connection = null;
		try {
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("GET");
			result = connection.getInputStream();
		} catch (final IOException e) {
			log.error("IO exception occured");
			e.printStackTrace();
		} finally {
		}

		return result;
	}
}